<?php

namespace App\Http\Controllers\Api;

use App\Libs\UcloudClient;
use App\Libs\WeChat\WxSmallClient;
use App\Models\user;
use App\Models\user_formid;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;
use Ixudra\Curl\Facades\Curl;

class TestController extends Controller
{
    public function sendtemp(Request $requests)
    {
        $id = $requests->json('id');
        $user = user::where('id', $id)->first();
        $template_id = 't9XzxP1iF_XunJHqENE1Ontqt6bOMYHAFvfoqoVcZE8';
        $page = 'pages/index/index';
        $formId = user_formid::select('id', 'form_id')->where(['openid'=>$user->openid])->orderBy('id', 'asc')->first();
        if (!$formId) {
            fun_respon(0, '为找到推送模板的formId');
        }
        //示例数据根据消息模板填充
        $data = array(
            'keyword1'=>array('value'=>'您参与的本宫翻脸活动可以领取礼物啦','color'=>'#7167ce'),
            'keyword2'=>array('value'=>'本宫鹰嘴脆一盒','color'=>'#7167ce'),
            'keyword3'=>array('value'=>'本宫PavoMea','color'=>'#7167ce')
        );
        $res = WxSmallClient::sendTemplate($user->openid, $data, $formId->form_id, $template_id);
        var_dump($res);
        // 删除用过的form_id
        user_formid::where('id', $formId->id)->delete();
    }

    public function send(){
        $user_info = user::take(2000)->skip(25000)->orderBy('id','ASC')->get(['openid'])->toArray();
        //var_dump($user_info);exit;
        if($user_info){
            $data = array(
                'keyword1'=>array('value'=>'本宫零食库悄悄开张，内有隐藏剧情','color'=>'#7167ce'),
                'keyword2'=>array('value'=>'本宫实验室神秘研发，全球最有情趣的零食初次预售，还有全场优惠哦','color'=>'#7167ce'),
            );
            $template_id = 'GcDsZ0ALQCGFmPXjVZtSD-3AZNvErBainA18W76_9bA';
            foreach ($user_info as $v){
                $formId = user_formid::lastformid($v['openid']);
                if (!$formId) {
                    savelog('no_push_user', 'openid=' . $v['openid']);
                    continue;
                }
                $res = WxSmallClient::sendTemplate($v['openid'], $data, $formId->form_id, $template_id,'pages/home/home');
                if (!isset($res['errcode']) || $res['errcode'] != 0) {
                    savelog('push_err_log', json_encode($res).'openid='.$v['openid'].'&form_id='.$formId->form_id);
                }
                // 删除用过的form_id
                user_formid::where('id', $formId->id)->delete();
                echo 'ok';
            }
        }

    }


    public function upload(){
        $avatar = (isset($_FILES['image']) && !empty($_FILES['image'])) ?$_FILES['image'] :'';
        if( empty($avatar) )
        {
            fun_respon(0,'缺少参数！');
        }
        if( $avatar['error'] != 0 || $avatar['size'] <= 0 )
        {
            fun_respon(0,'数据不能为空！');
        }

        $uploadclass = new UploadController();
        $img = $uploadclass->iosuploadimg($avatar);
        if( isset($img['code']) && !empty($img['code']))
        {
            $success = array(
                'url'=>$img['data']
            );
            fun_respon(1,$success);
        }
        fun_respon(0,'图片转移失败！');
    }

    public function test()
    {
        WxSmallClient::qrcodetest('id');
        exit;

        //var_dump(realpath(dirname(__FILE__)));
        $tem_img = 'qrcode_'.str_random(16) . '.png';

        $fp2 = fopen(public_path('/qrcode/qrcode_1Czu9cimF3iVDomS.png'), "r");
        //var_dump($fp2);
        //var_dump(date('Y-m-d H:s:i', time()));exit;
        var_dump($tem_img);
        $res = UcloudClient::minfileup($tem_img, public_path('/qrcode/qrcode_1Czu9cimF3iVDomS.png'));
        var_dump($res);


        $url = "https://api.weixin.qq.com/card/code/decrypt?access_token=11_YcLR93j5pfvZooyQv16OLivdE26i1FONvgjfIKbYq7FY8EWSbkz02o363FwbqTejIk1xdJs8C8qBdaYhNE8t7JpQby3EQGff332HA0gebzIsTFhth9jR9jbRMozLLXswMJTubNjN41s1yYmhVNOhACAJBC";
        $res = Curl::to( $url )
            ->withContentType('application/json')
            ->withData(json_encode(['encrypt_code'=>'1jmpyogY9DPMmJ%2BFqhfNCQHoJWUy36Lu8zBe83K2CeE%3D']))
            ->post();
        var_dump($res);
    }


    public function getToken(){

        header("Content-Type:text/html;charset=UTF-8");
        if(!isset($_FILES['code']))
        {
            fun_respon(0,'未上传选手信息');
        }
        if($_FILES['code']['error'] != 0 || $_FILES['code']['size'] <= 0)
        {
            fun_respon(0,'上传选手信息错误 ');
        }
        $filePath = $_FILES['code']['tmp_name'];
        $handle = fopen($filePath, 'r');
        $result = $this->input_csv($handle); //解析csv
        $len_result = count($result);
        if($len_result==0){
            echo '没有任何数据！';
            exit;
        }
        $data = [];
        //var_dump($result);exit;
        for ($i = 0; $i < $len_result; $i++)
        { //循环获取各字段值
            //$data[$i]['player_name'] = iconv('GBK', 'utf-8', $result[$i][0]);
            $data[$i]['created_at'] = $result[$i][0]/*.' '.$result[$i][1].":00:00"*/;
            $data[$i]['cpm_ct'] = $result[$i][1];
            $data[$i]['cpc_ct'] = $result[$i][2];
            $data[$i]['price'] = $result[$i][3];
            $data[$i]['total'] = $result[$i][4];
        }
        fclose($handle); //关闭指针
        $res = DB::table('test_statistics')->insert($data);

        $ress = DB::table('test_statistics')->get()->toArray();
        $ad_hourly = [];
        $user_hourly = [];
        foreach ($ress as $key=>$v){
            $tmp['ad_code'] = 'olGRNJJR';
            $tmp['time'] = $v->created_at;
            $tmp['cpc_ct'] = $v->cpc_ct;
            $tmp['cpm_ct'] = $v->cpm_ct;
            $tmp['cpm_avg'] = $v->total/$v->cpm_ct;
            $tmp['cpc_avg'] = $v->total/$v->cpc_ct;
            $ad_hourly[] = $tmp;

            $tmps['user_code'] = 'B6hhZNv7';
            $tmps['time'] = $v->created_at;
            $tmps['cpc_ct'] = $v->cpc_ct;
            $tmps['cpm_ct'] = $v->cpm_ct;
            $tmps['cpm_avg'] = $v->total/$v->cpm_ct;
            $tmps['cpc_avg'] = $v->total/$v->cpc_ct;
            $tmps['money_recharged'] = 0;
            $tmps['money_spent'] = $v->total;
            $user_hourly[] = $tmps;
        }
        $res = DB::table('wy_ad_statistics_hourly')->insert($ad_hourly);
        $res = DB::table('wy_user_ad_statistics_hourly')->insert($user_hourly);

        $sql = "SELECT DATE_FORMAT(created_at,'%Y-%m-%d') day,SUM(cpm_ct) as cpm_total,SUM(cpc_ct) as cpc_total,SUM(total) as totals FROM `test_statistics` GROUP BY day";
        $days = DB::select($sql);
        $ad_day = [];
        $user_day = [];
        foreach ($days as $value){
            $temp['ad_code'] = 'olGRNJJR';
            $temp['time'] = $value->day;
            $temp['cpc_ct'] = $value->cpc_total;
            $temp['cpm_ct'] = $value->cpm_total;
            $temp['cpm_avg'] = $value->totals/$value->cpm_total;
            $temp['cpc_avg'] = $value->totals/$value->cpc_total;
            $ad_day[] = $temp;

            $temps['user_code'] = 'B6hhZNv7';
            $temps['time'] = $value->day;
            $temps['cpc_ct'] = $value->cpc_total;
            $temps['cpm_ct'] = $value->cpm_total;
            $temps['cpm_avg'] = $value->totals/$value->cpm_total;
            $temps['cpc_avg'] = $value->totals/$value->cpc_total;
            $temps['money_recharged'] = 0;
            $temps['money_spent'] = $value->totals;
            $user_day[] = $temps;
        }
        $res = DB::table('wy_ad_statistics_daily')->insert($ad_day);
        $res = DB::table('wy_user_ad_statistics_daily')->insert($user_day);
        exit;

        /*$data = [];
        for ($i = 0 ; $i < $len_result; $i++){
            $data[$i]['phone'] = trim($result[$i][0]);
        }*/
        if(1)
        {
            echo 'success';
        }else
        {
            echo 'faits';
        }
        exit;

        /*$openid = 'o4plG4-hst5-b5gRGf2S3BIxRvuw';
        $token = Crypt::encrypt(['openid'=>$openid]);
        Redis::setex('experience_token_'.$openid, 14400, $token);
        var_dump($token);*/
    }


    function input_csv($handle)
    {
        $out = array ();
        $n = 0;
        while ($data = fgetcsv($handle, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        return $out;
    }

    public function gettest(Request $requests){
        $openid = $requests->openid;
        //获取用户信息
        $user_info = Redis::get('punch_user_info');
        if(!$user_info){
            fun_respon(0, '缺少用户信息!');
        }
        $user_info = json_decode($user_info,true);
        $this->bonus = $user_info['bonus'];



//            $token = Crypt::encrypt(['openid'=>'oyybT5BCvoLQU4WSKp-8d6UStm_Y']);
//            Redis::setex('punch_token_oyybT5BCvoLQU4WSKp-8d6UStm_Y', 14400, $token);
//            var_dump($token);
           //WxSmallClient::createdMemberCard();
    }

}
